package iqq;

import iqq.core.BasicMessenger;
import iqq.entity.User;
import iqq.util.OrderSafeProperties;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.io.IOUtils;

/**
 * 
 * Main Class
 * 
 * @author steven0lisa
 * @create-time Jul 27, 2012 6:45:22 PM
 */
public class App extends BasicMessenger implements Context {
	/**
	 * @param account
	 * @param password
	 */
	public App(String account, String password) {
		super(account, password);
	}

	/**
	 * name of app
	 */
	public static String name;
	
	/**
	 * version of app
	 */
	public static String version;

	/**
	 * The app configuration
	 */
	public static Properties configuration;

	/**
	 * configuration file for app
	 */
	public static final String CONFIG_FILE = "app.conf";

	public static void readConfiguration() {
		InputStream configInputStream = null;
		try {
			try {
				configInputStream = new FileInputStream(CONFIG_FILE);
			} catch (Exception e) {
				configInputStream = App.class.getResourceAsStream("/"+CONFIG_FILE);
			}
			configuration = new OrderSafeProperties();
			configuration.load(configInputStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (configInputStream != null) {
				IOUtils.closeQuietly(configInputStream);
			}
		}
	}

	/**
	 * App mode
	 */
	public static Mode mode;

	public static enum Mode {

		/**
		 * Enable development-specific features.
		 */
		DEV,
		/**
		 * Disable development-specific features.
		 */
		PROD;

		public boolean isDev() {
			return this == DEV;
		}

		public boolean isProd() {
			return this == PROD;
		}
	}

	public static List<Bootstrap> bootstraps = new ArrayList();
	static {
		bootstraps.add(new AppBootstrap());
		bootstraps.add(new LoggerBootstrap());
		bootstraps.add(new ThreadsBootstrap());
	}

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		for (Bootstrap b : bootstraps) {
			try {
				b.start();
			} catch (Exception e) {
				System.err.println("Error in bootstrap!" + e.toString());
				System.exit(-1);
			}
		}

		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				for (Bootstrap b : bootstraps) {
					try {
						b.stop();
					} catch (Exception e) {
					}
				}
			}
		});
	}

	/* @return owner 返回当前用户
	 * @see iqq.Context#getOwner()
	 */
	@Override
	public User getOwner() {
		return super.getOwner();
	}

}
